package com.cbj.netty.util;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import lombok.Data;
import sun.security.provider.PolicySpiFile;

import java.io.*;

/**
 * @author Godc
 * @description 常用的封装工具类
 */
@Data
public class RPCUtil {
    // 复用ByteArrayOutputStream，避免反复创建
    static ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    /**
     * 将对象转换为byte数组
     * @param target 要转换的对象，序列化
     * @return
     */
    public synchronized static byte[] getBytes(Object target){
        byteArrayOutputStream.reset();
        byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = null;
        try {
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(target);
            bytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 将byte数组转换为对象，反序列化
     * @param source
     * @param <T>
     * @return
     */
    public static <T>T getObject(byte[] source){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(source);
        T object = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            object = (T)objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return object;
    }
    public static ByteBuf comHeadAndContent(byte[] header,byte[] content){
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(header.length + content.length);
        byteBuf.writeBytes(header);
        byteBuf.writeBytes(content);
        return byteBuf;
    }
}
